package com.warm.system.service;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.warm.core.constant.Constants;
import com.warm.core.constant.UserConstants;
import com.warm.core.exception.ServiceException;
import com.warm.core.exception.user.*;
import com.warm.core.utils.DateUtils;
import com.warm.core.utils.MessageUtils;
import com.warm.core.utils.StringUtils;
import com.warm.core.utils.ip.IpUtils;
import com.warm.core.utils.sign.RsaUtils;
import com.warm.pom.satoken.utils.LoginUtils;
import com.warm.select.api.RedisCache;
import com.warm.select.constant.CacheConstants;
import com.warm.system.api.LoginUser;
import com.warm.system.api.domain.SysUser;
import com.warm.system.enums.UserStatus;
import com.warm.thread.manager.AsyncManager;
import com.warm.thread.manager.factory.AsyncFactory;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登录校验方法
 *
 * @author warm
 */
@Component
public class SysLoginService {
    protected final Logger log = LoggerFactory.getLogger(this.getClass());

    @Inject
    private RedisCache redisCache;

    @Inject
    private ISysUserService userService;

    @Inject
    private ISysConfigService configService;

    @Inject
    private TokenService tokenService;

    @Inject
    private SysPasswordService passwordService;

    @Inject
    private SysPermissionService permissionService;


    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        try {
            password = RsaUtils.decryptByPrivateKey(password);
        } catch (Exception e) {
            log.error("密码解密失败！");
            throw new UserLoginException();
        }
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        try {
            LoginUser loginUser = loadUserByUsername(username, password);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
            recordLoginInfo(loginUser.getUserId());
            StpUtil.login(loginUser.getUserId());
            LoginUtils.setLoginUser(loginUser);
            // 生成token
            return tokenService.createToken(loginUser);
        } catch (Exception e) {
            log.error("登录失败!", e);
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
            throw new ServiceException(e.getMessage());
        }
    }

    public void logout(Context ctx) {
        try {
            LoginUser loginUser = tokenService.getLoginUser(ctx);
            if (ObjectUtil.isNotNull(loginUser)) {
                String userName = loginUser.getUsername();
                // 删除用户缓存记录
                tokenService.delLoginUser(loginUser.getToken());
                // 记录用户退出日志
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, "退出成功"));
            }
            StpUtil.logout();
        } catch (Exception e) {
            log.error("登出失败！", e);
        } finally {
            StpUtil.logout();
        }
    }

    private LoginUser loadUserByUsername(String username, String password) {
        SysUser user = userService.selectUserByUserName(username);
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(password, user);

        return createLoginUser(user);
    }

    private LoginUser createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user
                , permissionService.getMenuPermission(user), permissionService.getRolePermission(user));
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    private void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StrUtil.emptyToDefault(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey, String.class);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    private void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    private void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
